package com.ibangnuo.manage.service.commission.api.impl;

import com.ibangnuo.framework.domain.Agent;
import com.ibangnuo.framework.domain.CommercialTenant;
import com.ibangnuo.framework.domain.CommissionDay;
import com.ibangnuo.framework.domain.Rate;
import com.ibangnuo.manage.dao.OrderMapper;
import com.ibangnuo.manage.dao.OrderRepository;
import com.ibangnuo.manage.dao.RateRepository;
import com.ibangnuo.manage.dao.commission.CommissionDayRepository;
import com.ibangnuo.manage.dao.commission.CommissionRepository;
import com.ibangnuo.manage.dao.employee.AgentMapper;
import com.ibangnuo.manage.dao.employee.AgentRepository;
import com.ibangnuo.manage.dao.employee.CommercialRepository;
import com.ibangnuo.manage.service.commission.api.CommissionQueryStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: wwy
 * @Date: 2020-03-13 9:35
 */
@Component
public class DayCommissionQuery implements CommissionQueryStrategy {
    private static Logger LOGGER = LoggerFactory.getLogger(DayCommissionQuery.class);

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private AgentRepository agentRepository;
    @Autowired
    private CommercialRepository commercialRepository;
    @Autowired
    private AgentMapper agentMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RateRepository rateRepository;
    @Autowired
    private CommissionRepository commissionRepository;
    @Autowired
    private CommissionDayRepository commissionDayRepository;

    /**
     * 1.in查询出每个代理商 下商户的订单信息，订单信息(前一天的)
     * 2.查询出每个代理商的id,根据代理商id,查询出每个商户id,进行信息的统计
     */
    @Override
    public void query() {
        ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();

        Calendar calendar = new GregorianCalendar();
        calendar.setTime(new Date());
        calendar.add(calendar.DATE,-1);
        //昨天时间
        Date yesDate = calendar.getTime();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String yesDateFormatStarter = simpleDateFormat.format(yesDate)+"00:00:00";
        String yesDateFormatEnd = simpleDateFormat.format(yesDate)+"23:59:59";
        SimpleDateFormat starterDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String,List<String>> agentOrder = new HashMap<>();//key:代理商id value:商户list集合
        try {
            Date starterTime = starterDateFormat.parse(yesDateFormatStarter);
            Date endTime = starterDateFormat.parse(yesDateFormatEnd);
            //根据时间查询出每个商户订单信息
            List<Agent> agentList = agentRepository.findByIsDelete(1);
            List<String> agentIdList = new ArrayList<>();//代理商id集合
            for (Agent agent : agentList) {
                agentIdList.add(agent.getId());
            }
            for (String agentId : agentIdList) {
                List<CommercialTenant> commercialTenantList = commercialRepository.findByAgentIdAndIsDelete(agentId, 1);
                List<String> commercialIdList = new ArrayList<>();
                for (CommercialTenant commercialTenant : commercialTenantList) {
                    commercialIdList.add(commercialTenant.getId());
                }
                agentOrder.put(agentId,commercialIdList);

            }
            //代理商信息结果
            Map<String,Map<String,Object>> agentPayMap = new HashMap<>();
            //查询每个代理商的商户的订单总金额，支付宝金额，微信金额
            Map<String,Object> payCountParam = new HashMap<>();//查询条件
            payCountParam.put("startTime",starterTime);
            payCountParam.put("endTime",endTime);
            for (Map.Entry<String, List<String>> agentOrderEntry : agentOrder.entrySet()) {
                Map<String,Object> resultMap = new HashMap<>();
                String agentId = agentOrderEntry.getKey();
                List<String> commercialIdList = agentOrderEntry.getValue();
                payCountParam.put("list",commercialIdList);
                payCountParam.put("payWay",0);//支付宝
                Map<String, Object> resultAliMap = orderMapper.discountsCommissionAlipayNew(payCountParam);
                int totalAliPaycounts = 0;
                int aliPayMoney = 0;
                if(resultAliMap != null){
                    totalAliPaycounts = (int) resultAliMap.get("totalPaycounts");
                    aliPayMoney = (int) resultAliMap.get("payMoney");
                }


                payCountParam.put("payWay",1);//微信
                Map<String, Object> resultWxMap = orderMapper.discountsCommissionAlipayNew(payCountParam);
                int totalWxPaycounts = 0;
                int wxPayMoney = 0;
                if(resultWxMap != null){
                    totalWxPaycounts = (int) resultWxMap.get("totalPaycounts");
                    wxPayMoney = (int) resultWxMap.get("payMoney");
                }

                payCountParam.put("payWay",00);//全部
                Map<String, Object> resultAllMap = orderMapper.discountsCommissionAlipayNew(payCountParam);
                int totalAllPaycounts = 0;
                int allPayMoney = (int) 0;
                if(resultAllMap != null){
                    totalAllPaycounts = (int) resultAllMap.get("totalPaycounts");
                    allPayMoney = (int) resultAllMap.get("payMoney");
                }

                resultMap.put("totalAliPaycounts",totalAliPaycounts);
                resultMap.put("aliPayMoney",aliPayMoney);
                resultMap.put("totalWxPaycounts",totalWxPaycounts);
                resultMap.put("wxPayMoney",wxPayMoney);
                resultMap.put("totalAllPaycounts",totalAllPaycounts);
                resultMap.put("allPayMoney",allPayMoney);
                resultMap.put("agentId",agentId);
                agentPayMap.put(agentId,resultMap);
            }
            Map<String,Map<String,Double>> threeMap = new HashMap<>();//全部三级代理统计信息
            //查询三级代理
            List<Agent> threeAgentList = agentRepository.findByHierarchyAndIsDelete("1-2-3", 1);
            //遍历map得到这些代理的信息，并保存进入数据库
            for (Agent agent : threeAgentList) {
                Map<String,Double> threePayMap = new HashMap<>();
                Rate aliRate = rateRepository.findByAcIdAndPayWay(agent.getId(), 0);//支付宝费率
                Rate wxRate = rateRepository.findByAcIdAndPayWay(agent.getId(), 0);//微信费率
                Map<String, Object> resultMap = agentPayMap.get(agent.getId());
                CommissionDay commissionDay = new CommissionDay();
                commissionDay.setAgentId(agent.getId());
                double aliPayMoney = (Double.parseDouble(String.valueOf(resultMap.get("aliPayMoney"))) / 100)*(Double.parseDouble(aliRate.getRate()));
                commissionDay.setAliPay((int)(aliPayMoney*100));
                double wxPayMoney = (Double.parseDouble(String.valueOf(resultMap.get("wxPayMoney"))) / 100)*(Double.parseDouble(wxRate.getRate()));
                commissionDay.setWxPay((int)(wxPayMoney*100));
                commissionDay.setSum((int)(aliPayMoney*100)+(int)(wxPayMoney*100));
                commissionDay.setCreateTime(new Date());
                String monthDate = simpleDateFormat.format(yesDate);
                commissionDay.setMonthDate(monthDate);
                commissionDayRepository.save(commissionDay);
                threePayMap.put("aliPayMoney",aliPayMoney);
                threePayMap.put("wxPayMoney",wxPayMoney);
                threeMap.put(agent.getId(),threePayMap);
            }


            Map<String,Map<String,Double>> twoMap = new HashMap<>();//全部二级代理统计信息（包含子级的）
            //查询二级代理,并根据二级代理查询三级代理
            List<Agent> twoAgentList = agentRepository.findByHierarchyAndIsDelete("1-2", 1);
            for (Agent agent : twoAgentList) {
                Map<String,Double> twoPayMap = new HashMap<>();
                Rate aliRate = rateRepository.findByAcIdAndPayWay(agent.getId(), 0);//支付宝费率
                Rate wxRate = rateRepository.findByAcIdAndPayWay(agent.getId(), 0);//微信费率
                Map<String, Object> resultMap = agentPayMap.get(agent.getId());
                Double aliPayMoneySum = 0.0;
                Double wxPayMoneySum = 0.0;
                for (Agent threeAgent : threeAgentList) {
                    Map<String, Double> threePayMap = threeMap.get(threeAgent.getId());
                    aliPayMoneySum = aliPayMoneySum + threePayMap.get("aliPayMoney");
                    wxPayMoneySum = wxPayMoneySum + threePayMap.get("wxPayMoney");

                }
                CommissionDay commissionDay = new CommissionDay();
                commissionDay.setAgentId(agent.getId());
                aliPayMoneySum = aliPayMoneySum + (Double.parseDouble(String.valueOf(resultMap.get("aliPayMoney"))) / 100)*(Double.parseDouble(aliRate.getRate()));
                wxPayMoneySum = wxPayMoneySum + (Double.parseDouble(String.valueOf(resultMap.get("wxPayMoney"))) / 100)*(Double.parseDouble(wxRate.getRate()));
                commissionDay.setAliPay((int)(aliPayMoneySum*100));
                commissionDay.setWxPay((int)(wxPayMoneySum*100));
                commissionDay.setSum((int)(aliPayMoneySum*100)+(int)(wxPayMoneySum*100));
                commissionDay.setCreateTime(new Date());
                String monthDate = simpleDateFormat.format(yesDate);
                commissionDay.setMonthDate(monthDate);
                commissionDayRepository.save(commissionDay);
                twoPayMap.put("aliPayMoney",aliPayMoneySum);
                twoPayMap.put("wxPayMoney",wxPayMoneySum);
                twoMap.put(agent.getId(),twoPayMap);
            }

            //一级代理，业务原因，所有二级代理相加，加上自己的
            List<Agent> oneAgentList = agentRepository.findByHierarchyAndIsDelete("1", 1);
            Map<String,Double> onePayMap = new HashMap<>();
            Rate aliRate = rateRepository.findByAcIdAndPayWay(oneAgentList.get(0).getId(), 0);//支付宝费率
            Rate wxRate = rateRepository.findByAcIdAndPayWay(oneAgentList.get(0).getId(), 0);//微信费率
            Map<String, Object> resultMap = agentPayMap.get(oneAgentList.get(0).getId());
            CommissionDay commissionDay = new CommissionDay();
            commissionDay.setAgentId(oneAgentList.get(0).getId());
            Double aliPayMoneySum = 0.0;
            Double wxPayMoneySum = 0.0;
            for (Map.Entry<String, Map<String, Double>> twoPayMap : twoMap.entrySet()) {
                Map<String, Double> value = twoPayMap.getValue();
                aliPayMoneySum = aliPayMoneySum + value.get("aliPayMoney");
                wxPayMoneySum = wxPayMoneySum + value.get("wxPayMoney");
            }
            aliPayMoneySum = aliPayMoneySum + (Double.parseDouble(String.valueOf(resultMap.get("aliPayMoney"))) / 100)*(Double.parseDouble(aliRate.getRate()));
            wxPayMoneySum = wxPayMoneySum + (Double.parseDouble(String.valueOf(resultMap.get("wxPayMoney"))) / 100)*(Double.parseDouble(wxRate.getRate()));
            commissionDay.setAliPay((int)(aliPayMoneySum*100));
            commissionDay.setWxPay((int)(wxPayMoneySum*100));
            commissionDay.setSum((int)(aliPayMoneySum*100)+(int)(wxPayMoneySum*100));
            commissionDay.setCreateTime(new Date());
            String monthDate = simpleDateFormat.format(yesDate);
            commissionDay.setMonthDate(monthDate);
            commissionDayRepository.save(commissionDay);
        } catch (Exception e) {
            LOGGER.error("日佣金统计异常",e.getMessage());

        }

    }
}
